package com.pope.framework.triage.modular.service;

import com.pope.framework.constants.Constants;
import com.pope.framework.constants.RescueWhereAboutsEnum;
import com.pope.framework.constants.TriageStatus;
import com.pope.framework.constants.TriageWhereAboutsEnum;
import com.pope.framework.core.util.DecimalUtil;
import com.pope.framework.core.util.StringUtil;
import com.pope.framework.dict.modular.entity.DictComplaints;
import com.pope.framework.dict.modular.entity.DictComplaintsD;
import com.pope.framework.dict.modular.entity.DictExamination;
import com.pope.framework.dict.modular.entity.DictNorm;
import com.pope.framework.dict.modular.entity.DictStrength;
import com.pope.framework.dict.modular.service.DictComplaintsDService;
import com.pope.framework.dict.modular.service.DictComplaintsService;
import com.pope.framework.dict.modular.service.DictExaminationService;
import com.pope.framework.dict.modular.service.DictNormService;
import com.pope.framework.dict.modular.service.DictSicknessGradeService;
import com.pope.framework.dict.modular.service.DictStrengthService;
import com.pope.framework.kernel.model.enums.YesOrNotEnum;
import com.pope.framework.kernel.model.exception.ServiceException;
import com.pope.framework.rescue.modular.dto.RescueInfoDto;
import com.pope.framework.rescue.modular.entity.RescueInfo;
import com.pope.framework.rescue.modular.service.RescueInfoService;
import com.pope.framework.statistics.modular.dto.TriageInfoListDto;
import com.pope.framework.statistics.modular.vo.DepartNumberVo;
import com.pope.framework.statistics.modular.vo.GradeNumberVo;
import com.pope.framework.statistics.modular.vo.TriageInfoListVo;
import com.pope.framework.third.ThirdUtil;
import com.pope.framework.triage.modular.dto.ComplaintDto;
import com.pope.framework.triage.modular.dto.TriageInfoDto;
import com.pope.framework.triage.modular.dto.ValueDto;
import com.pope.framework.triage.modular.entity.ComingWay;
import com.pope.framework.triage.modular.entity.ComplaintsInfo;
import com.pope.framework.triage.modular.entity.EscortPerson;
import com.pope.framework.triage.modular.entity.GradeInfo;
import com.pope.framework.triage.modular.entity.GrageChangeLog;
import com.pope.framework.triage.modular.entity.GreenChannel;
import com.pope.framework.triage.modular.entity.TriageEpidemic;
import com.pope.framework.triage.modular.entity.TriageExamination;
import com.pope.framework.triage.modular.entity.TriageInfo;
import com.pope.framework.triage.modular.entity.TriageLogInfo;
import com.pope.framework.triage.modular.entity.TriageNorm;
import com.pope.framework.triage.modular.entity.TriageNormLog;
import com.pope.framework.triage.modular.entity.TriageNormLogTotal;
import com.pope.framework.triage.modular.entity.TriageNumber;
import com.pope.framework.triage.modular.mapper.TriageInfoMapper;
import com.pope.framework.triage.modular.vo.ComplaintClassifyVo;
import com.pope.framework.triage.modular.vo.ComplaintVo;
import com.pope.framework.triage.modular.vo.DictGradeVo;
import com.pope.framework.triage.modular.vo.TriageInfoVo;
import com.pope.framework.triage.modular.vo.TriageSimpleInfoVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 分诊信息 服务实现类
 * </p>
 *
 * @author superpope
 * @since 2019-01-14
 */
@Service
@Transactional
@Slf4j
public class TriageInfoService extends ServiceImpl<TriageInfoMapper, TriageInfo> {

	@Autowired
	private ComingWayService comingWayService;
	@Autowired
	private EscortPersonService escortPersonService;
	@Autowired
	private GreenChannelService greenChannelService;
	@Autowired
	private ComplaintsInfoService complaintsInfoService; 
	@Autowired
	private DictComplaintsService dictComplaintsService;
	@Autowired
	private DictComplaintsDService dictComplaintsDService;
	@Autowired
	private TriageNumberService triageNumberService;
	@Autowired
	private TriageLogInfoService triageLogInfoService;
	@Autowired
	private DictStrengthService dictStrengthService;
	
	@Autowired
	private GradeInfoService gradeInfoService;
	@Autowired
	private TriageNormService triageNormService;
	
	@Autowired
	private GrageChangeLogService grageChangeLogService;
	@Autowired
	private ThirdUtil thirdUtil;
	@Autowired
	private RescueInfoService rescueInfoService;
	
	@Autowired
	private  TriageEpidemicService triageEpidemicService;
	
	@Autowired
	private TriageExaminationService triageExaminationService;
	
	@Autowired
	private DictExaminationService dictExaminationService;
	
	@Autowired
	private DictSicknessGradeService dictSicknessGradeService;
	
	@Autowired
	private TriageNormLogService triageNormLogService;
	
	@Autowired
	private TriageNormLogTotalService tirageNormLogTotalService;
	@Autowired
	private DictNormService dictNormService;
	
	
	private Object object=new Object();
	public Integer insert(TriageInfoDto triageInfoDto) {
		
		TriageInfo triageInfo=new TriageInfo();
		BeanUtil.copyProperties(triageInfoDto, triageInfo);
		if((triageInfo.getComingGrade()!=null && triageInfo.getComingGrade()!=0)
				|| (triageInfo.getAutoGrade()!=null && triageInfo.getAutoGrade()!=0)
				) {
			triageInfo.setTriageState(TriageStatus.YPG.getCode()+"");
		}else {
			triageInfo.setTriageState(TriageStatus.DPG.getCode()+"");
		}
		triageInfo.setVersion(0);
//		triageInfo.setCreateTime(DateUtil.now());
//		triageInfo.setUpdateTime(DateUtil.now());
		
		TriageNumber queryTriageNumber=new TriageNumber();
		queryTriageNumber.setHospitalId(triageInfoDto.getHospitalId());
		queryTriageNumber.setCurrentDate1(com.pope.framework.core.util.DateUtil.getCurrentDateStr());
		QueryWrapper<TriageNumber> queryTriageNumberWrapper=new QueryWrapper<>();
		queryTriageNumberWrapper.setEntity(queryTriageNumber);
		queryTriageNumberWrapper.orderByDesc("CURRENT_NUMBER");
		TriageNumber triageNumber=triageNumberService.getOne(queryTriageNumberWrapper);
		if(triageNumber==null) {
			triageNumber=new TriageNumber();
			triageNumber.setCurrentDate1(com.pope.framework.core.util.DateUtil.getCurrentDateStr());
			triageNumber.setCurrentNumber(1);
			triageNumber.setVersion(1);
			triageNumber.setHospitalId(triageInfoDto.getHospitalId());
			triageNumberService.save(triageNumber);
		}else {
			triageNumber.setCurrentNumber(triageNumber.getCurrentNumber()+1);
			boolean numberFlag=triageNumberService.updateById(triageNumber);
			if(!numberFlag) {
				throw new ServiceException("分诊信息添加失败!");
			}
		}
		
	//	Integer currentNumber=1;
		//synchronized (object) {
//			TriageNumber queryTriageNumber=new TriageNumber();
//			queryTriageNumber.setCurrentDate1(DateUtil.formatDate(DateUtil.date()));
//			QueryWrapper<TriageNumber> queryTriageNumberWrapper=new QueryWrapper<>();
//			queryTriageNumberWrapper.setEntity(queryTriageNumber);
//			 triageNumber=triageNumberService.getOne(queryTriageNumberWrapper);
//			if(triageNumber==null) {
//				triageNumber=new TriageNumber();
//				triageNumber.setCurrentDate1(DateUtil.formatDate(DateUtil.date()));
//				triageNumber.setCurrentNumber(1);
//				currentNumber=1;
//			}else {
//				currentNumber=triageNumber.getCurrentNumber()+1;
//				triageNumber.setCurrentNumber(triageNumber.getCurrentNumber()+1);
//			}
		//急诊编号生成规则：日期+时间+当日5位流水号，如2018.10.11 13:22登记的当天第一位患者，则急诊编号为：20181011132200001
		String time=com.pope.framework.core.util.DateUtil.getCurrentDateTimeStr().replace("-", "").replace(" ", "").replace(":","");
		time=time.substring(0, time.length()-2);
		
		String emerencyNumber=triageInfoDto.getHospitalId()+time+StrUtil.fillBefore(StringUtil.toStr(triageNumber.getCurrentNumber()), '0', 5);
		triageInfo.setEmergencyNumber(emerencyNumber);
		if(StrUtil.isEmpty(triageInfo.getComingChannel())) {
			triageInfo.setComingChannel("");
		}
		if(StrUtil.isEmpty(triageInfo.getComingChannelHospital())) {
			triageInfo.setComingChannelHospital("");
		}
			boolean flag=this.save(triageInfo);
			if(!flag) {
				throw new ServiceException("分诊信息添加失败，请重写确认！");
			}
			//2019-02-15 去掉新增分级日志
//			if(StringUtil.toInt(triageInfoDto.getComingGrade())!=StringUtil.toInt(triageInfoDto.getChangeGrade())) {
//				this.saveChangeGrageLog(triageInfoDto.getComingGrade(), triageInfoDto.getChangeGrade(), triageInfoDto.getChangeGradeReson(), triageInfo.getId(), triageInfo.getHospitalId());
//			}
			
			saveTriageExtend(triageInfoDto, triageInfo);
			
			//保存变更日志
			TriageLogInfo saveTriageLogInfo=new TriageLogInfo();
			BeanUtil.copyProperties(triageInfo, saveTriageLogInfo);
			if(TriageWhereAboutsEnum.HJ.getCode().equals(triageInfo.getWhereAbouts())) {
				triageInfo.setToHospital(Constants.NULL_VALUE);
				triageInfo.setDepart(Constants.NULL_VALUE);
			}else if(TriageWhereAboutsEnum.ZY.getCode().equals(triageInfo.getWhereAbouts())) {
				triageInfo.setDepart(Constants.NULL_VALUE);
			}else {
				triageInfo.setToHospital(Constants.NULL_VALUE);
			}
			saveTriageLogInfo.setId(null);
			saveTriageLogInfo.setTriageId(triageInfo.getId());
			saveTriageLogInfo.setHospitalId(triageInfo.getHospitalId());
			triageLogInfoService.save(saveTriageLogInfo);
//			if(StrUtil.isEmpty(triageNumber.getId())) {
//				triageNumberService.save(triageNumber);
//			}else {
//				triageNumberService.updateById(triageNumber);
//			}
		//}
		
		insertRescueInfo(triageInfo);
		return triageInfo.getId();
	}
	
	
	private void insertRescueInfo(TriageInfo triageInfo) {
		if(TriageWhereAboutsEnum.QJS.getCode().equals(triageInfo.getWhereAbouts())
	    		||TriageWhereAboutsEnum.LGS.getCode().equals(triageInfo.getWhereAbouts())) {
	    	RescueInfoDto rescueInfoDto=new RescueInfoDto();
	    	rescueInfoDto.setHospitalId(triageInfo.getHospitalId());
	    	rescueInfoDto.setPatientId(triageInfo.getPatientId());
	    	rescueInfoDto.setRescueTime(DateUtil.now());
	    	if(TriageWhereAboutsEnum.QJS.getCode().equals(triageInfo.getWhereAbouts())) {
	    		rescueInfoDto.setRescueWhereAbouts(RescueWhereAboutsEnum.QJS.getCode());
	    	}else {
	    		rescueInfoDto.setRescueWhereAbouts(RescueWhereAboutsEnum.LGS.getCode());
	    	}
	    	rescueInfoDto.setTriageId(triageInfo.getId());
	    	rescueInfoService.insert(rescueInfoDto);
	    }
	}
	private void deleteTriageExtend(TriageInfo triageInfo) {
		ComingWay deleteComingWay=new ComingWay();
		deleteComingWay.setTriageId(triageInfo.getId());
		UpdateWrapper<ComingWay> deleteComingWayWrapper=new UpdateWrapper<>();
		deleteComingWayWrapper.setEntity(deleteComingWay);
		comingWayService.remove(deleteComingWayWrapper);
		
		EscortPerson deleteEscortPerson=new EscortPerson();
		deleteEscortPerson.setTriageId(triageInfo.getId());
		UpdateWrapper<EscortPerson> deleteEscortPersonWrapper=new UpdateWrapper<>();
		deleteEscortPersonWrapper.setEntity(deleteEscortPerson);
		escortPersonService.remove(deleteEscortPersonWrapper);
		
		GreenChannel deleteGreenChannel=new GreenChannel();
		deleteGreenChannel.setTriageId(triageInfo.getId());
		UpdateWrapper<GreenChannel> deleteGreenChannelWrapper=new UpdateWrapper<>();
		deleteGreenChannelWrapper.setEntity(deleteGreenChannel);
		greenChannelService.remove(deleteGreenChannelWrapper);
		
		ComplaintsInfo deleteComplaintsInfo=new ComplaintsInfo();
		deleteComplaintsInfo.setTriageId(triageInfo.getId());
		UpdateWrapper<ComplaintsInfo> deleteComplaintsInfoWrapper=new UpdateWrapper<>();
		deleteComplaintsInfoWrapper.setEntity(deleteComplaintsInfo);
		complaintsInfoService.remove(deleteComplaintsInfoWrapper);
		
		TriageNorm deleteTriageNorm=new TriageNorm();
		deleteTriageNorm.setTriageId(triageInfo.getId());
		UpdateWrapper<TriageNorm> deleteTriageNormWrapper=new UpdateWrapper<>();
		deleteTriageNormWrapper.setEntity(deleteTriageNorm);
		triageNormService.remove(deleteTriageNormWrapper);
		
		//流行学病史
		TriageEpidemic deleteTriageEpidemic=new TriageEpidemic();
		deleteTriageEpidemic.setTriageId(triageInfo.getId());
		UpdateWrapper<TriageEpidemic> deleteTriageEpidemicWrapper=new UpdateWrapper<>();
		deleteTriageEpidemicWrapper.setEntity(deleteTriageEpidemic);
		triageEpidemicService.remove(deleteTriageEpidemicWrapper);
		
		
		//检伤依据
		TriageExamination deleteTriageExamination=new TriageExamination();
		deleteTriageExamination.setTriageId(triageInfo.getId());
		UpdateWrapper<TriageExamination> deleteTriageExaminationWrapper=new UpdateWrapper<>();
		deleteTriageExaminationWrapper.setEntity(deleteTriageExamination);
		triageExaminationService.remove(deleteTriageExaminationWrapper);
		
	}
	
	private void saveChangeGrageLog(Integer oldValue,Integer newValue,String content,Integer triageId,Integer hospitalId,List<ValueDto> liveNorms) {
		GrageChangeLog saveGrageChangeLog=new GrageChangeLog();
		saveGrageChangeLog.setChangeGradeReson(content);
		saveGrageChangeLog.setHospitalId(hospitalId);
		saveGrageChangeLog.setNewGradeCode(newValue);
		saveGrageChangeLog.setOldGradeCode(oldValue);
		saveGrageChangeLog.setTriageId(triageId);
		grageChangeLogService.save(saveGrageChangeLog);
	
	}
	private void saveTriageExtend(TriageInfoDto triageInfoDto,TriageInfo triageInfo) {
		//来院方式
				List<ComingWay> comingWays=CollUtil.newArrayList();
				//线删除后插入
				if(CollUtil.isNotEmpty(triageInfoDto.getComingWays())) {
					triageInfoDto.getComingWays().forEach(comingWay->{
						ComingWay saveComingWay=new ComingWay();
						comingWays.add(saveComingWay);
						saveComingWay.setTriageId(triageInfo.getId());
						saveComingWay.setWayId(comingWay);
					});
					comingWayService.saveBatch(comingWays);
				}
				
				//陪送人员
				
				List<EscortPerson> escortPersons=CollUtil.newArrayList();
				if(CollUtil.isNotEmpty(triageInfoDto.getEscorts())) {
					triageInfoDto.getEscorts().forEach(escort->{
						EscortPerson saveEscorePerson=new EscortPerson();
						escortPersons.add(saveEscorePerson);
						saveEscorePerson.setEscortId(escort);
						saveEscorePerson.setTriageId(triageInfo.getId());
					});
					escortPersonService.saveBatch(escortPersons);
				}
				//绿色通道
				
				List<GreenChannel> greenChannels=CollUtil.newArrayList();
				if(CollUtil.isNotEmpty(triageInfoDto.getGreenChanels())) {
					triageInfoDto.getGreenChanels().forEach(greenChanel->{
						GreenChannel saveGreenChannel=new GreenChannel();
						greenChannels.add(saveGreenChannel);
						saveGreenChannel.setChannelId(greenChanel);
						saveGreenChannel.setTriageId(triageInfo.getId());
					});
					greenChannelService.saveBatch(greenChannels);
				}
				
				//主诉
				List<ComplaintsInfo> complaints=CollUtil.newArrayList();
				if(CollUtil.isNotEmpty(triageInfoDto.getComplaints())) {
					triageInfoDto.getComplaints().forEach(complaintDto->{
						ComplaintsInfo saveComplaintsInfo=new ComplaintsInfo();
						complaints.add(saveComplaintsInfo);
						saveComplaintsInfo.setStrength(complaintDto.getStrengthId());
						saveComplaintsInfo.setTriageId(triageInfo.getId());
						saveComplaintsInfo.setComplaintsId(complaintDto.getComplaintId());
					});
					complaintsInfoService.saveBatch(complaints);
				}
				
			List<TriageNorm> triageNorms=CollUtil.newArrayList();
			if(CollUtil.isNotEmpty(triageInfoDto.getLiveNorms())) {
				triageInfoDto.getLiveNorms().forEach(data->{
					TriageNorm triageNorm=new TriageNorm();
					triageNorm.setNormId(data.getCode());
					triageNorm.setTriageId(triageInfo.getId());
					triageNorm.setValue(data.getValue());
					triageNorms.add(triageNorm);
				});
				triageNormService.saveBatch(triageNorms);
			}
			//流行学病史
			List<TriageEpidemic> triageEpidemics=CollUtil.newArrayList();
			if(CollUtil.isNotEmpty(triageInfoDto.getEpidemics())) {
				triageInfoDto.getEpidemics().forEach(data->{
					TriageEpidemic triageEpidemic=new TriageEpidemic();
					triageEpidemic.setEpidemicCode(data);
					triageEpidemic.setTriageId(triageInfo.getId());
					triageEpidemics.add(triageEpidemic);
				});
				triageEpidemicService.saveBatch(triageEpidemics);
			}
			
			List<TriageExamination> triageExaminations=CollUtil.newArrayList();
			if(CollUtil.isNotEmpty(triageInfoDto.getExaminations())) {
				triageInfoDto.getExaminations().forEach(data->{
					TriageExamination triageExamination=new TriageExamination();
					triageExamination.setExaminationCode(data);
					triageExamination.setTriageId(triageInfo.getId());
					triageExaminations.add(triageExamination);
				});
				triageExaminationService.saveBatch(triageExaminations);
			}
	}
	
	public Integer modify(TriageInfoDto triageInfoDto) {
		TriageInfo oldTriageInfo=this.getById(triageInfoDto.getId());
		TriageInfo triageInfo=new TriageInfo();
		BeanUtil.copyProperties(triageInfoDto, triageInfo);
		if((triageInfo.getComingGrade()!=null && triageInfo.getComingGrade()!=0)
				|| (triageInfo.getAutoGrade()!=null && triageInfo.getAutoGrade()!=0)
				) {
			triageInfo.setTriageState(TriageStatus.YPG.getCode()+"");
		}else {
			triageInfo.setTriageState(TriageStatus.DPG.getCode()+"");
		}
		triageInfo.setCreatetime(null);
		triageInfo.setCreateMan(null);
		triageInfo.setEmergencyNumber(null);
		
		if(StrUtil.isEmpty(triageInfo.getComingChannel())) {
			triageInfo.setComingChannel("");
		}
		if(StrUtil.isEmpty(triageInfo.getComingChannelHospital())) {
			triageInfo.setComingChannelHospital("");
		}
		if(TriageWhereAboutsEnum.HJ.getCode().equals(triageInfo.getWhereAbouts())) {
			triageInfo.setToHospital(Constants.NULL_VALUE);
			triageInfo.setDepart(Constants.NULL_VALUE);
		}else if(TriageWhereAboutsEnum.ZY.getCode().equals(triageInfo.getWhereAbouts())) {
			triageInfo.setDepart(Constants.NULL_VALUE);
		}else {
			triageInfo.setToHospital(Constants.NULL_VALUE);
		}
		int version=StringUtil.toInt(oldTriageInfo.getVersion(),0);
		
		//判断是否是首次调整更改后等级
		if(version==0) {
			if(StringUtil.toInt(triageInfo.getChangeGrade(),0)!=0) {
				version=1;
				if(StringUtil.toInt(triageInfo.getComingGrade(),0)!=0) {
					if(StringUtil.toInt(triageInfo.getComingGrade(),0)!=StringUtil.toInt(triageInfo.getChangeGrade(),0)) {
						this.saveChangeGrageLog(oldTriageInfo.getComingGrade(), triageInfo.getChangeGrade(), triageInfo.getChangeGradeReson(), triageInfo.getId(),triageInfo.getHospitalId(),triageInfoDto.getLiveNorms());
					}
				}else {
					if(StringUtil.toInt(triageInfo.getAutoGrade(),0)!=StringUtil.toInt(triageInfo.getChangeGrade(),0)) {
						this.saveChangeGrageLog(oldTriageInfo.getAutoGrade(), triageInfo.getChangeGrade(), triageInfo.getChangeGradeReson(), triageInfo.getId(),triageInfo.getHospitalId(),triageInfoDto.getLiveNorms());
					}
				}
				
			}
		}else {
			version=1;
			if(StringUtil.toInt(triageInfo.getChangeGrade(),0)!=StringUtil.toInt(oldTriageInfo.getChangeGrade(),0)) {
				this.saveChangeGrageLog(oldTriageInfo.getChangeGrade(), triageInfo.getChangeGrade(), triageInfo.getChangeGradeReson(), triageInfo.getId(),triageInfo.getHospitalId(),triageInfoDto.getLiveNorms());
			}
		}
		triageInfo.setVersion(version);
		
		
		boolean hasSaveLogTotal=false;
		
//	    //意识状态是否变化
//	    if(!Convert.toStr(oldTriageInfo.getConsciousState(),"").equals(Convert.toStr(triageInfo.getConsciousState(),""))){
//	    	this.tirageNormLogTotalService.save(saveTriageNormLogTotal);
//	    	hasSaveLogTotal=true;
//	    	TriageNormLog saveTriageNormLog=new TriageNormLog();
//	    	 saveTriageNormLog.setNewLiveValue(triageInfo.getConsciousState());
//	    	 saveTriageNormLog.setOldLiveValue(oldTriageInfo.getConsciousState());
//	    	 saveTriageNormLog.setLogId(saveTriageNormLogTotal.getId());
//	         saveTriageNormLog.setHospitalId(triageInfoDto.getHospitalId()); 
//	 		 triageNormLogService.save(saveTriageNormLog);
//	    }
		//保存生命体征变更日志
		saveLiveNormsLog(triageInfoDto);
	    
		//boolean flag=this.updateById(triageInfo);
		UpdateWrapper<TriageInfo> uw = new UpdateWrapper<>();
		uw.set("PATIENT_ID", triageInfo.getPatientId());
		uw.set("THREE_NO_STAFF", triageInfo.getThreeNoStaff());
		uw.set("COMING_WAY_REMARK", triageInfo.getComingWayRemark());
		
		uw.set("MYOCARDIAL_INFARCTION", triageInfo.getMyocardialInfarction());
		uw.set("CONSCIOUS_STATE", triageInfo.getConsciousState());
		uw.set("COMING_GRADE", triageInfo.getComingGrade());
		uw.set("CHANGE_GRADE", triageInfo.getChangeGrade());
		uw.set("AUTO_GRADE", triageInfo.getAutoGrade());
		uw.set("WHERE_ABOUTS", triageInfo.getWhereAbouts());
		uw.set("DEPART", triageInfo.getDepart());
		//uw.set("updatetime", val);
		//uw.set("TRIAGE_STATE", triageInfo.getTriageState());
		uw.set("TO_HOSPITAL", triageInfo.getToHospital());
		//uw.set("VERSION", triageInfo.getVersion());
		uw.set("CHANGE_GRADE_RESON", triageInfo.getChangeGradeReson());
		uw.set("CONTENT", triageInfo.getContent());
		
		uw.set("REMARK", triageInfo.getRemark());
		//uw.set("STAFF_ID", triageInfo.getStaffId());
		uw.eq("ID", triageInfo.getId());
		
		this.baseMapper.update(triageInfo, uw);
//		if(!flag) {
//			throw new ServiceException("分诊信息修改失败，请重写确认！");
//		}
		
		
		
		
		deleteTriageExtend(triageInfo);
		saveTriageExtend(triageInfoDto, triageInfo);
		//保存变更日志
		TriageLogInfo saveTriageLogInfo=new TriageLogInfo();
		BeanUtil.copyProperties(triageInfo, saveTriageLogInfo);
		saveTriageLogInfo.setId(null);
		saveTriageLogInfo.setTriageId(triageInfo.getId());
		triageLogInfoService.save(saveTriageLogInfo);
		insertRescueInfo(triageInfo);
		return triageInfo.getId();
		
	}
	
	
	private void saveLiveNormsLog(TriageInfoDto triageInfoDto) {
		 TriageNorm queryTriageNorm=new TriageNorm();
		    queryTriageNorm.setTriageId(triageInfoDto.getId());
		    QueryWrapper<TriageNorm> queryTriageNormWrapper=new QueryWrapper<>();
		    queryTriageNormWrapper.setEntity(queryTriageNorm);
		    
		   List<TriageNorm> oldTriageNorms= triageNormService.list(queryTriageNormWrapper);
		    List<DictNorm> dictNorms=dictNormService.list();
		    TriageNormLogTotal saveTriageNormLogTotal=new TriageNormLogTotal();
			saveTriageNormLogTotal.setTriageId(triageInfoDto.getId());
			saveTriageNormLogTotal.setHospitalId(triageInfoDto.getId());
			boolean hasChange=false;
		    if(CollUtil.isNotEmpty(dictNorms)) {
		    	//判断是否发生变化
		    	for(DictNorm dictNorm:dictNorms) {
		    		TriageNorm oldTriageNorm=null;
		    		ValueDto newTriageNorm=null;
		    		if(CollUtil.isNotEmpty(oldTriageNorms)) {
		    			for(TriageNorm triageNorm:oldTriageNorms) {
		    				if(triageNorm.getNormId().equals(dictNorm.getCode())) {
		    					oldTriageNorm=triageNorm;
		    				}
		    			}
		    		}
		    		
		    		if(CollUtil.isNotEmpty(triageInfoDto.getLiveNorms())) {
		    			for(ValueDto valueDto:triageInfoDto.getLiveNorms()) {
		    				if(valueDto.getCode().equals(dictNorm.getCode())) {
		    					newTriageNorm=valueDto;
		    				}
		    			}
		    		}
		    		if(oldTriageNorm!=null && newTriageNorm!=null) {
		    			if(DecimalUtil.toDecimal(oldTriageNorm.getValue()).compareTo(DecimalUtil.toDecimal(newTriageNorm.getValue()))!=0) {
		    				hasChange=true;
		    			}
		    		}else {
		    			if(newTriageNorm != null) {
		    				hasChange=true;
		    			}else if(oldTriageNorm!=null) {
		    				hasChange=true;
		    			}
		    		}
		    		
		    	}
		    }
		   if(hasChange) {
			   tirageNormLogTotalService.save(saveTriageNormLogTotal);
			   for(DictNorm dictNorm:dictNorms) {
		    		TriageNorm oldTriageNorm=null;
		    		ValueDto newTriageNorm=null;
		    		if(CollUtil.isNotEmpty(oldTriageNorms)) {
		    			for(TriageNorm triageNorm:oldTriageNorms) {
		    				if(triageNorm.getNormId().equals(dictNorm.getCode())) {
		    					oldTriageNorm=triageNorm;
		    				}
		    			}
		    		}
		    		
		    		if(CollUtil.isNotEmpty(triageInfoDto.getLiveNorms())) {
		    			for(ValueDto valueDto:triageInfoDto.getLiveNorms()) {
		    				if(valueDto.getCode().equals(dictNorm.getCode())) {
		    					newTriageNorm=valueDto;
		    				}
		    			}
		    		}
    				TriageNormLog saveTriageNormLog=new TriageNormLog();
    				if(oldTriageNorm!=null) {
    					saveTriageNormLog.setOldLiveValue(Convert.toStr(oldTriageNorm.getValue()));
    				}
    				if(newTriageNorm!=null) {
    					saveTriageNormLog.setNewLiveValue(Convert.toStr(newTriageNorm.getValue()));
    				}
    				
    				saveTriageNormLog.setLogId(saveTriageNormLogTotal.getId());
    				saveTriageNormLog.setHospitalId(triageInfoDto.getHospitalId());
    				saveTriageNormLog.setNormId(dictNorm.getCode());
    				triageNormLogService.save(saveTriageNormLog);
		    	}
		   }
	}
	public boolean delete(Integer id) {
		TriageInfo triageInfo=this.getById(id);
		if(triageInfo==null) {
			throw new ServiceException("该分诊信息不存在，请重写确认！");
		}
		RescueInfo queryRescueInfo=new RescueInfo();
		queryRescueInfo.setTriageId(id);
		QueryWrapper<RescueInfo> queryWrapper=new QueryWrapper<>();
		queryWrapper.setEntity(queryRescueInfo);
		
		int count=rescueInfoService.count(queryWrapper);
		if(count>0) {
			throw new ServiceException("该分诊信息已被离抢记录使用，您无法删除！");
		}
		this.deleteTriageExtend(triageInfo);
		boolean flag=this.removeById(id);
		if(!flag) {
			throw new ServiceException("该分诊信息不存在，请重写确认！");
		}
		return flag;
	}
	
	 public IPage<TriageSimpleInfoVo> listSimple(Page<TriageSimpleInfoVo> page, Integer id,String name,String beginDate,
			 String endDate,String emergencyNumber,String triageState,Integer hospitalId){
		 //主诉字典表
		 DictComplaintsD queryDictComplaintsD=new DictComplaintsD();
		 QueryWrapper<DictComplaintsD> queryDictComplaintsDWrapper=new QueryWrapper<>();
		 queryDictComplaintsDWrapper.setEntity(queryDictComplaintsD);
		 queryDictComplaintsDWrapper.orderByAsc("orders");
		 
		 List<DictComplaintsD> dictComplaintsDs=dictComplaintsDService.list(queryDictComplaintsDWrapper);
		 
		 IPage<TriageSimpleInfoVo> datas= baseMapper.selectSimpleList(page, id, name, beginDate, endDate,emergencyNumber,triageState,hospitalId);
		 
		 if(CollUtil.isNotEmpty(datas.getRecords())) {
			 List<Map<String,Object>> departs=thirdUtil.getDeparts(hospitalId);
			 for(TriageSimpleInfoVo triageSimpleInfoVo:datas.getRecords()) {
				 triageSimpleInfoVo.setComplaintNames(this.getComplaintNames(triageSimpleInfoVo.getId(), dictComplaintsDs));
				 triageSimpleInfoVo.setDepartName(thirdUtil.getDepartName(departs, triageSimpleInfoVo.getDepartId()));
				  
			 }
		 }
		 return datas;
	 }
	 
	 public Integer selectPatientsNumber(String beginDate,String endDate,Integer hospitalId,String whereAbouts,String triageState) {
		 return baseMapper.selectPatientsNumber(beginDate, endDate, hospitalId,whereAbouts,triageState);
	 }
	 
	 /**
	  * 统计科室当前人数
	  * @param beginDate
	  * @param endDate
	  * @param hospitalId
	  * @return
	  */
	 public List<DepartNumberVo> selectPatientsNumberByDepart(String beginDate, String endDate,Integer hospitalId,String tirageState){
		 List<DepartNumberVo> lst=baseMapper.selectPatientsNumberByDepart(beginDate, endDate, hospitalId,tirageState);
		 List<Map<String,Object>> departs=thirdUtil.getDeparts(hospitalId);
		 List<DepartNumberVo> values=CollUtil.newArrayList();
		 if(CollUtil.isNotEmpty(departs)) {
			 for(Map<String,Object> depart:departs) {
				 String departId=StringUtil.toStr(depart.get("id"));
				 DepartNumberVo departNumberVo=getDepartNumberVo(departId,lst);
				 if(departNumberVo==null) {
					 departNumberVo=new DepartNumberVo();
					 departNumberVo.setNumber(0);
				 }
				 departNumberVo.setDepartName(StringUtil.toStr(depart.get("name")));
				 values.add(departNumberVo);
			 }
		 }
		 values.sort(new Comparator<DepartNumberVo>() {

			@Override
			public int compare(DepartNumberVo o1, DepartNumberVo o2) {
				if(o1.getNumber()>o2.getNumber()) {
					return -1;
				}else if(o1.getNumber()<o2.getNumber()) {
					return 1;
				}else {
					return 0;
				}
			}
		});
		 return values;
	 }
	 
	 private DepartNumberVo getDepartNumberVo(String depart,List<DepartNumberVo> lst) {
		 if(CollUtil.isNotEmpty(lst)) {
			 for(DepartNumberVo vo:lst) {
				 if(depart.equals(StringUtil.toStr(vo.getDepart()))) {
					 return vo;
				 }
			 }
		 }
		 return null;
	 }
	 
	 /**
	  * 统计分级当前人数
	  * @param beginDate
	  * @param endDate
	  * @param hospitalId
	  * @return
	  */
	 public List<GradeNumberVo> selectPatientsNumberByGrade( String beginDate, String endDate,Integer hospitalId,String tirageState){
		 List<GradeNumberVo> lst=baseMapper.selectPatientsNumberByGrade(beginDate, endDate, hospitalId,tirageState);
		 List<GradeNumberVo> values=CollUtil.newArrayList();
		 GradeInfo queryGradeInfo=new GradeInfo();
//		 if(hospitalId!=null) {
//			 queryGradeInfo.setHospitalId(hospitalId);
//		 }
		 QueryWrapper<GradeInfo> queryGradeInfoWrapper=new QueryWrapper<>();
		 queryGradeInfoWrapper.setEntity(queryGradeInfo);
		 queryGradeInfoWrapper.orderByAsc("danger");
		 List<GradeInfo>  gradeInfos=gradeInfoService.list(queryGradeInfoWrapper);
		 if(CollUtil.isNotEmpty(gradeInfos)) {
			 for(GradeInfo gradeInfo:gradeInfos) {
				 GradeNumberVo vo=getGradeNumberVo(StringUtil.toStr(gradeInfo.getId()),lst);
				 if(vo==null) {
					 vo=new GradeNumberVo();
					 vo.setNumber(0);
				 }
				 vo.setGrade(gradeInfo.getId());
				 vo.setGradeName(gradeInfo.getName());
				 values.add(vo);
			 }
		 }
		return  values;
	 }
	 
	 private GradeNumberVo getGradeNumberVo(String grade,List<GradeNumberVo> lst) {
		 if(CollUtil.isNotEmpty(lst)) {
			 for(GradeNumberVo vo:lst) {
				 if(grade.equals(StringUtil.toStr(vo.getGrade()))) {
					 return vo;
				 }
			 }
		 }
		 return null;
	 }
	 
	 /**
	  * 获取生命特征值完整度
	  * @param beginDate
	  * @param endDate
	  * @param hospitalId
	  * @return
	  */
	 public List<Map<String,Object>> getNormBl(String beginDate,String endDate,Integer hospitalId,String triageState){
		 QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		 String sql="";
		 if(StrUtil.isNotBlank(beginDate)) {
			 queryWrapper.ge("UPDATETIME", beginDate);
			 sql+=" AND UPDATETIME>='"+beginDate+"' ";
		 }
		 if(StrUtil.isNotBlank(endDate)) {
			 queryWrapper.le( "UPDATETIME", endDate);
			 sql+=" AND UPDATETIME<='"+endDate+"' ";
		 }
		 if(hospitalId!=null) {
			 queryWrapper.eq("HOSPITAL_ID", hospitalId);
			 sql+=" AND HOSPITAL_ID='"+hospitalId+"' ";
		 }
		 if(StrUtil.isNotBlank(triageState)) {
			 queryWrapper.eq("TRIAGE_STATE", triageState);
			 sql+=" AND TRIAGE_STATE='"+triageState+"' ";
		 }
		 
		 List<Map<String,Object>> result=CollUtil.newArrayList();
		 int count=this.count(queryWrapper);
		 List<DictNorm> dictNorms=dictNormService.list();
		 if(CollUtil.isNotEmpty(dictNorms)) {
			 for(DictNorm dictNorm:dictNorms) {
				 Map<String,Object> data=BeanUtil.beanToMap(dictNorm);
				 result.add(data);
				 QueryWrapper<TriageNorm> queryTriageNormWrapper=new QueryWrapper<>();
				 queryTriageNormWrapper.gt("VALUE", 0);
				 queryTriageNormWrapper.inSql("TRIAGE_ID", "SELECT ID FROM T_TRIAGE_TRIAGE_INFO WHERE 1=1 "+sql);
				 queryTriageNormWrapper.eq("NORM_ID", dictNorm.getCode());
				 int childCount=triageNormService.count(queryTriageNormWrapper);
				 data.put("totalnum", count);
				 data.put("changenum", childCount);
				 if(count==0) {
					 data.put("bl", 0);
				 }else {
					 data.put("bl", NumberUtil.mul(NumberUtil.div(childCount, count, 4), 100));
				 }
				 
			 }
		 }
		 return result;
	 }
	 /**
	  * 查询分诊明细列表
	  * @param triageInfoListDto
	  * @return
	  */
	 public IPage<TriageInfoListVo>  selectTriageStaticsDetail(Page<TriageInfoListVo> page,TriageInfoListDto triageInfoListDto){
		 if(StrUtil.isNotBlank(triageInfoListDto.getBeginDate())) {
			 if(triageInfoListDto.getBeginDate().length()==10) {
				 triageInfoListDto.setBeginDate(triageInfoListDto.getBeginDate()+" 00:00:00"); 
			 }
		 }
		 if(StrUtil.isNotBlank(triageInfoListDto.getEndDate())) {
			 if(triageInfoListDto.getEndDate().length()==10) {
				 triageInfoListDto.setEndDate(triageInfoListDto.getEndDate()+" 24:00:00"); 
			 }
		 }
		 List<DictExamination> dictExaminations=dictExaminationService.list();
		 IPage<TriageInfoListVo> datas= baseMapper.selectTriageStaticsDetail(page,triageInfoListDto);
		 if(CollUtil.isNotEmpty(datas.getRecords())) {
			 List<DictComplaintsD> dictComplaintsD=dictComplaintsDService.list();
			 List<Map<String,Object>> departs=thirdUtil.getDeparts(triageInfoListDto.getHospitalId());
			for(TriageInfoListVo vo:datas.getRecords()) {
					 vo.setDepartName(thirdUtil.getDepartName(departs, vo.getDepart()));
					 vo.setComplaintNames(this.getComplaintNames(vo.getId(), dictComplaintsD));
					 
					 
					 vo.setDictExaminatons(CollUtil.newArrayList());
					 
					 TriageExamination queryTriageExamination=new TriageExamination();
						queryTriageExamination.setTriageId(vo.getId());
						
						QueryWrapper<TriageExamination> queryTriageExaminationWrapper=new QueryWrapper<>();
						queryTriageExaminationWrapper.setEntity(queryTriageExamination);
						List<TriageExamination> triageExaminations=triageExaminationService.list(queryTriageExaminationWrapper);
						if(CollUtil.isNotEmpty(triageExaminations) && CollUtil.isNotEmpty(dictExaminations)) {
							triageExaminations.forEach(triageExamination->{
								dictExaminations.forEach(dictExamination->{
									if(triageExamination.getExaminationCode().equals(dictExamination.getCode())) {
										DictGradeVo dictVo=new DictGradeVo();
										BeanUtil.copyProperties(dictExamination, dictVo);
										vo.getDictExaminatons().add(dictVo);
									}
									
								});
							});
						}
			}
			 		
		 }
		 return datas;
	 }
	 
	 
	 public String getComplaintNames(Integer triageId ,List<DictComplaintsD> dictComplaintsDs) {
		 ComplaintsInfo queryComplaintsInfo=new ComplaintsInfo();
		 queryComplaintsInfo.setTriageId(triageId);
		 log.info("==========complaintNames3=="+triageId);
		 QueryWrapper<ComplaintsInfo> queryComplaintsInfoWrapper=new QueryWrapper<>();
		 queryComplaintsInfoWrapper.setEntity(queryComplaintsInfo);
		  List<ComplaintsInfo> complaintsInfos=  complaintsInfoService.list(queryComplaintsInfoWrapper);
		  log.info("==========complaintNames1==");
		  if(CollUtil.isNotEmpty(complaintsInfos) && CollUtil.isNotEmpty(dictComplaintsDs)) {
			  String complaintNames="";
			  
			  for(DictComplaintsD dictComplaintsD:dictComplaintsDs) {
				  for(ComplaintsInfo complaintsInfo:complaintsInfos) {
					  if(dictComplaintsD.getCode().equals(complaintsInfo.getComplaintsId())) {
						  complaintNames+=","+dictComplaintsD.getName();
						  continue;
					  }
				  }
			  }
			  if(StrUtil.isNotEmpty(complaintNames)) {
				  complaintNames=complaintNames.substring(1);
			  }
			  log.info("==========complaintNames2=="+complaintNames);
			  return complaintNames;
		  }
		  return "";
	 }
	 
	 
	 public List<ComplaintClassifyVo> getComplaintClassify(Integer triageId,List<DictComplaintsD> dictComplaintsD,List<DictComplaints>  dictComplaints,List<DictStrength> dictStrengths){
		//获取主诉		
			ComplaintsInfo queryComplaintsInfo=new ComplaintsInfo();
			queryComplaintsInfo.setTriageId(triageId);
			QueryWrapper<ComplaintsInfo> queryComplaintsInfoWrapper=new QueryWrapper<>();
			queryComplaintsInfoWrapper.setEntity(queryComplaintsInfo);
			List<ComplaintsInfo> complaintsInfos=complaintsInfoService.list(queryComplaintsInfoWrapper);
			List<ComplaintClassifyVo> complaintClassifyVos=CollUtil.newArrayList();
			if(CollUtil.isNotEmpty(complaintsInfos) && CollUtil.isNotEmpty(dictComplaints) && CollUtil.isNotEmpty(dictComplaintsD)) {
				complaintsInfos.forEach(complaintInfo->{
					String classifyCode="";
					ComplaintVo complaintVo=null;
					for(DictComplaintsD dict:dictComplaintsD) {
						if(dict.getCode().equals(complaintInfo.getComplaintsId())) {
							classifyCode=dict.getClassifyCode();
							//BeanUtil.copyProperties(dict, complaintVo);
							if(complaintVo==null) {
								complaintVo=new ComplaintVo();
							}
							complaintVo.setCompaintId(dict.getCode());
							complaintVo.setCompaintName(dict.getName());
							
							break;
						}
					}
					//获取强度
					for(DictStrength dict:dictStrengths) {
						if(dict.getCode().equals(complaintInfo.getStrength())) {
							if(complaintVo==null) {
								complaintVo=new ComplaintVo();
							}
							complaintVo.setStrengthId(dict.getCode());
							complaintVo.setStrengthName(dict.getName());
							break;
						}
					}
					
					
					
					ComplaintClassifyVo existVo=checkcomplaintClassifyHas(complaintClassifyVos,classifyCode);
					if(existVo==null) {
						for(DictComplaints dict:dictComplaints) {
							if(dict.getCode().equals(classifyCode)) {
								existVo=new ComplaintClassifyVo();
								
								existVo.setClassifyId(dict.getCode());
								existVo.setName(dict.getName());
								existVo.setComplaints(CollUtil.newArrayList());
								existVo.getComplaints().add(complaintVo);
								complaintClassifyVos.add(existVo);
								break;
							}
						}
					}else {
						existVo.getComplaints().add(complaintVo);
					}
					
				});
				
			}
			return complaintClassifyVos;
	 }
	 private ComplaintClassifyVo checkcomplaintClassifyHas(List<ComplaintClassifyVo> complaintClassifyVos,String code) {
			if(CollUtil.isNotEmpty(complaintClassifyVos)) {
				for(ComplaintClassifyVo classify:complaintClassifyVos) {
					if(classify.getClassifyId().equals(code)) {
						return classify;
					}
				}
			}
			return null;
		}
	 
	 /**
	  * 分级变更率统计
	  */
	 public Map<String,Object> selectPerChangeGrage(String beginDate,String endDate,Integer hospitalId ,String triageState){
		 QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		 String sql="";
		 if(StrUtil.isNotBlank(beginDate)) {
			 queryWrapper.ge("UPDATETIME", beginDate);
			 sql+=" AND UPDATETIME>='"+beginDate+"' ";
		 }
		 if(StrUtil.isNotBlank(endDate)) {
			 queryWrapper.le( "UPDATETIME", endDate);
			 sql+=" AND UPDATETIME<='"+endDate+"' ";
		 }
		 if(hospitalId!=null) {
			 queryWrapper.eq("HOSPITAL_ID", hospitalId);
			 sql+=" AND HOSPITAL_ID='"+hospitalId+"' ";
		 }
		 if(StrUtil.isNotBlank(triageState)) {
			 queryWrapper.eq("TRIAGE_STATE", triageState);
			 sql+=" AND TRIAGE_STATE='"+triageState+"' ";
		 }
		 Map<String,Object> result=CollUtil.newHashMap();
		 int count=this.count(queryWrapper);
		 result.put("totalnum", count);
		 QueryWrapper<GrageChangeLog> queryGrageChangeLogWrapper=new QueryWrapper<>();
		 queryGrageChangeLogWrapper.select("count(distinct triage_id) as changenum");
		 queryGrageChangeLogWrapper.inSql("TRIAGE_ID", "SELECT ID FROM T_TRIAGE_TRIAGE_INFO WHERE 1=1 "+sql);
		 Map<String,Object> changeMap=grageChangeLogService.getMap(queryGrageChangeLogWrapper);
		 int childCount=Convert.toInt(changeMap.get("changenum"),0);
		 result.put("changenum", childCount);
		 if(count==0) {
			 result.put("bl", 0);
		 }else {
			 result.put("bl", NumberUtil.mul(NumberUtil.div(childCount, count, 4), 100));
		 }
		 return result;
//		 Map<String,Object> data=this.baseMapper.selectPerChangeGrage(beginDate, endDate, hospitalId,triageState);
//		 if(MapUtil.isNotEmpty(data)) {
//			 Integer totalNum=Convert.toInt(data.get("totalnum"),0);
//			 Integer changenum=Convert.toInt(data.get("changenum"),0);
//			 data.put("changenum", changenum);
//			 if(totalNum==0) {
//				 data.put("bl", 0);
//			 }else {
//				 data.put("bl", NumberUtil.mul(NumberUtil.div(changenum,totalNum,  4), 100));
//			 }
//			 
//		 }
//		 return data;
	 }
	 
}
